/*********************************************************************************
 *      Copyright:  (C) 2024 ioter<ioter@gmail.com>
 *                  All rights reserved.
 *
 *       Filename:  server2.c
 *    Description:  This file 
 *                 
 *        Version:  1.0.0(06/07/24)
 *         Author:  ioter <ioter@gmail.com>
 *      ChangeLog:  1, Release initial version on "06/07/24 11:05:49"
 *                 
 ********************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <openssl/ssl.h>
#include <openssl/err.h>
#include <pthread.h>

#define SERVER_PORT 4433
#define BUFFER_SIZE 1024

void initialize_openssl()
{
    SSL_load_error_strings();
    OpenSSL_add_ssl_algorithms();
}

void cleanup_openssl()
{
    EVP_cleanup();
}

SSL_CTX *create_context()
{
    const SSL_METHOD *method;
    SSL_CTX *ctx;

    method = SSLv23_server_method();
    ctx = SSL_CTX_new(method);
    if (!ctx)
    {
        perror("Unable to create SSL context");
        ERR_print_errors_fp(stderr);
        exit(EXIT_FAILURE);
    }
    return ctx;
}

void configure_context(SSL_CTX *ctx)
{
    SSL_CTX_set_ecdh_auto(ctx, 1);

    // Set the certificate and key
    if (SSL_CTX_use_certificate_file(ctx, "server.crt", SSL_FILETYPE_PEM) <= 0)
    {
        ERR_print_errors_fp(stderr);
        exit(EXIT_FAILURE);
    }

    if (SSL_CTX_use_PrivateKey_file(ctx, "server.key", SSL_FILETYPE_PEM) <= 0)
    {
        ERR_print_errors_fp(stderr);
        exit(EXIT_FAILURE);
    }
}

void handle_client(SSL *ssl)
{
    char buffer[BUFFER_SIZE];
    int bytes;

    if (SSL_accept(ssl) <= 0)
    {
        ERR_print_errors_fp(stderr);
    }
    
    while(1)
	{
        bytes = SSL_read(ssl, buffer, sizeof(buffer));
        if (bytes > 0)
        {
            buffer[bytes] = 0;
            printf("Received message: %s\n", buffer);
            SSL_write(ssl, buffer, strlen(buffer));
        }
        else
        {
            ERR_print_errors_fp(stderr);
        }
    }

    SSL_shutdown(ssl);
    SSL_free(ssl);
}

void *client_handler(void *arg)
{
    SSL *ssl = (SSL *)arg;
    handle_client(ssl);
    pthread_exit(NULL);
}

int main()
{
    int server_sock;
    struct sockaddr_in addr;
    SSL_CTX *ctx;

    initialize_openssl();
    ctx = create_context();
    configure_context(ctx);

    server_sock = socket(AF_INET, SOCK_STREAM, 0);
    if (server_sock < 0)
    {
        perror("Unable to create socket");
        exit(EXIT_FAILURE);
    }

    addr.sin_family = AF_INET;
    addr.sin_port = htons(SERVER_PORT);
    addr.sin_addr.s_addr = htonl(INADDR_ANY);

    if (bind(server_sock, (struct sockaddr *)&addr, sizeof(addr)) < 0)
    {
        perror("Unable to bind");
        exit(EXIT_FAILURE);
    }

    if (listen(server_sock, 1) < 0)
    {
        perror("Unable to listen");
        exit(EXIT_FAILURE);
    }

    printf("Server is listening on port %d...\n", SERVER_PORT);

    while (1)
    {
        struct sockaddr_in addr;
        uint len = sizeof(addr);
        SSL *ssl;

        int client_sock = accept(server_sock, (struct sockaddr *)&addr, &len);
        if (client_sock < 0)
        {
            perror("Unable to accept");
            exit(EXIT_FAILURE);
        }

        printf("New connection, socket fd is %d, ip is : %s, port : %d\n",
               client_sock, inet_ntoa(addr.sin_addr), ntohs(addr.sin_port));

        ssl = SSL_new(ctx);
        SSL_set_fd(ssl, client_sock);

        pthread_t tid;
        if (pthread_create(&tid, NULL, client_handler, ssl) != 0)
        {
            perror("Unable to create thread");
            SSL_free(ssl);
            close(client_sock);
        }
        pthread_detach(tid);
    }

    close(server_sock);
    SSL_CTX_free(ctx);
    cleanup_openssl();
}

